<script setup lang="ts">
import { onMounted } from 'vue';
import { showLoading, getCurrentInstance, showToast, navigateTo, showModal } from '@tarojs/taro';
import EmergencyStepList from '../../components/emergency-step-list.vue';
import EmergencyPersonList from '../../components/emergency-person-list.vue';
import {
  EMERGENCY_DRILL_APP_DETAIL,
  EMERGENCY_DRILL_APP_OPERATE,
} from '/@/api/modules/base/emergency-drill';
import { state } from './state';
import dayjs from 'dayjs';
import { beginTimeEndTimeConvert } from '/@/utils/time';

/**
 * @description 当前路由信息
 */
const params = getCurrentInstance().router?.params as unknown as {
  id: string;
};

/**
 * 是否点击跳过或者已完成
 */
let isNextStep = false;
function queryDetail() {
  showLoading();
  EMERGENCY_DRILL_APP_DETAIL({ dto: { id: params.id } }).then((res) => {
    //点击完成所有步骤跳转到完成页面
    if (isNextStep && res.emergencyDrillDto?.status === 2) {
      navigateTo({
        url: '/pages/emergency-manage/drill/submit-success/index',
      });
      return;
    }
    state.emergencyDrillDto = res.emergencyDrillDto;
    state.emergencyMemberDtos = res.emergencyMemberDtos;
    state.emergencyDrillStepDtos = res.emergencyDrillStepDtos;
    state.emergencyPlanFileDtos = res.emergencyPlanFileDtos;
    state.leader = res.leader;
  });
}

onMounted(() => {
  isNextStep = false;
  queryDetail();
});

/**
 * 先确认再开始
 */
function startConfirm() {
  showModal({
    title: '开始演练',
    content: '确认开始演练吗？',
    success: (res) => {
      if (!res.confirm) return;
      start();
    },
  });
}

/**
 * 开始演练
 */
function start() {
  showLoading();
  if (!state.emergencyDrillStepDtos || state.emergencyDrillStepDtos.length === 0) {
    showToast({ title: '数据错误，不能开始演练', icon: 'error' });
    return;
  }
  EMERGENCY_DRILL_APP_OPERATE({
    id: params.id,
    operateType: 1,
    stepId: state.emergencyDrillStepDtos[0].id,
  }).then(() => {
    queryDetail();
  });
}

/**
 * 先确认再开始
 */
function stepCompleteConfirm() {
  showModal({
    title: '已完成演练',
    content: '确认已完成演练吗？',
    success: (res) => {
      res.confirm && stepComplete();
    },
  });
}

/**
 * 完成演练
 */
function stepComplete() {
  if (!state.emergencyDrillStepDtos || state.emergencyDrillStepDtos.length === 0) {
    showToast({ title: '数据错误，不能完成演练', icon: 'error' });
    return;
  }
  showLoading();
  EMERGENCY_DRILL_APP_OPERATE({
    id: params.id,
    operateType: 3,
    stepId: state.emergencyDrillStepDtos[0].id,
  }).then(() => {
    isNextStep = true;
    queryDetail();
  });
}

/**
 * 先确认再开始
 */
function stepJumpConfirm() {
  showModal({
    title: '跳过演练',
    content: '确认跳过演练吗？',
    success: (res) => {
      if (!res.confirm) return;
      stepJump();
    },
  });
}

/**
 * 跳过演练
 */
function stepJump() {
  if (!state.emergencyDrillStepDtos || state.emergencyDrillStepDtos.length === 0) {
    showToast({ title: '数据错误，不能跳过演练', icon: 'error' });
    return;
  }
  showLoading();
  EMERGENCY_DRILL_APP_OPERATE({
    id: params.id,
    operateType: 2,
    stepId: state.emergencyDrillStepDtos[0].id,
  }).then(() => {
    isNextStep = true;
    queryDetail();
  });
}

/**
 * 演练时间结束页面跳转
 */
function timeEndPage() {
  navigateTo({
    url: '/pages/emergency-manage/drill/submit-success/index?timeEnd=true',
  });
}
</script>

<template>
  <view class="drill-detail app-page--1">
    <app-navbar title="演练详情" />
    <scroll-view class="app-page__wrapper" :scroll-y="true" :lower-threshold="100">
      <view class="drill-detail__wrapper">
        <nut-cell-group>
          <nut-cell>
            <template #title>
              <view class="drill-detail__title-wrapper">
                <view class="drill-detail__title">
                  {{ state.emergencyDrillDto?.name || '-' }}
                </view>
                <view
                  class="drill-detail__status"
                  :class="{
                    'drill-detail__status-complete': state.emergencyDrillDto?.status === 2,
                  }"
                  >{{ state.emergencyDrillDto?.status === 2 ? '已结束' : '未完成' }}</view
                >
              </view>
              <view class="drill-detail__time">
                演练时间:&nbsp;&nbsp;{{
                  state.emergencyDrillDto?.beginTime
                    ? dayjs(state.emergencyDrillDto?.beginTime).format('YYYY-MM-DD HH:mm')
                    : '-'
                }}
                ~
                {{
                  state.emergencyDrillDto?.endTime
                    ? dayjs(state.emergencyDrillDto?.endTime).format('YYYY-MM-DD HH:mm')
                    : '-'
                }}
              </view>
              <!-- 演练进行中  -->
              <view
                v-if="
                  state.emergencyDrillDto?.realBeginTime && state.emergencyDrillDto?.status === 1
                "
              >
                <nut-countdown
                  format="剩余时间:&nbsp;&nbsp;<span>DD</span> 天 <span>HH</span> 小时 <span>mm</span> 分 <span>ss</span> 秒"
                  :end-time="state.emergencyDrillDto?.endTime"
                  @on-end="timeEndPage"
                >
                </nut-countdown>
              </view>
            </template>
          </nut-cell>
          <nut-cell v-if="state.emergencyDrillDto?.status === 2">
            <template #title>
              <nut-row v-if="state.emergencyDrillDto?.score">
                <nut-col :span="12">
                  <view class="drill-detail__title">
                    演练评分:&nbsp;&nbsp;{{ state.emergencyDrillDto?.score }}
                  </view>
                </nut-col>
                <nut-col :span="12">
                  <view class="drill-detail__title">
                    总用时:&nbsp;&nbsp;{{
                      state.emergencyDrillDto.realBeginTime && state.emergencyDrillDto.realEndTime
                        ? beginTimeEndTimeConvert(
                            state.emergencyDrillDto.realBeginTime,
                            state.emergencyDrillDto.realEndTime,
                          )
                        : '-'
                    }}
                  </view>
                </nut-col>
              </nut-row>
            </template>
          </nut-cell>
          <nut-cell>
            <template #title>
              <view>
                <view class="drill-detail__title">处置步骤</view>
                <emergency-step-list
                  :list="state.emergencyDrillStepDtos"
                  :status="state.emergencyDrillDto?.status"
                />
              </view>
            </template>
          </nut-cell>
          <!-- 开始演练前和结束演练后展示联系人 -->
          <nut-cell
            v-if="!state.emergencyDrillDto?.realBeginTime || state.emergencyDrillDto?.status === 2"
          >
            <template #title>
              <view>
                <view class="drill-detail__title">应急小组</view>
                <emergency-person-list :list="state.emergencyMemberDtos" />
              </view>
            </template>
          </nut-cell>
        </nut-cell-group>
      </view>
    </scroll-view>
    <view v-if="state.leader">
      <!-- 开始演练 -->
      <view
        class="drill-detail__footer"
        v-if="!state.emergencyDrillDto?.realBeginTime && state.emergencyDrillDto?.status === 1"
      >
        <nut-button block type="info" @click="startConfirm()"> 开始演练 </nut-button>
      </view>
      <!-- 演练进行中  -->
      <view
        class="drill-detail__footer"
        v-else-if="state.emergencyDrillDto?.realBeginTime && state.emergencyDrillDto?.status === 1"
      >
        <nut-button
          class="drill-detail__footer-btn"
          block
          type="warning"
          @click="stepJumpConfirm()"
        >
          跳过
        </nut-button>
        <nut-button
          class="drill-detail__footer-btn"
          block
          type="info"
          @click="stepCompleteConfirm()"
        >
          已完成
        </nut-button>
      </view>
    </view>
  </view>
</template>

<style lang="scss">
@import './index.scss';
</style>
